package cn.tanglong.topic;

import cn.tanglong.direct.Producer04;
import cn.tanglong.mq.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class topic2 {

    public static final String QUEUE_NAME = "QUEUE_NAME";

    public static void main(String[] args) throws Exception {
        //获取连接
        Connection connection = ConnectionUtil.getConnection();
        //创建与Exchange的通道，每个连接可以创建多个通道，每个通道代表一个会话任务
        Channel channel = connection.createChannel();

        // 创建队列
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);

        // 绑定队列到交换机
        channel.queueBind(QUEUE_NAME, Producer05.EXCHANGE_TOPIC, "error.#");

        // 同时只处理一条消息，把堆积的消息转给其他通道
        channel.basicQos(1);

        // 拿到一个队列消息
        Consumer callback = new DefaultConsumer(channel){

            // 重写这方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消息名 = " + new String(body));
                System.out.println("consumerTag = " + consumerTag);
                System.out.println("交换机 = " + envelope.getExchange());
                System.out.println("队列 = " + envelope.getRoutingKey());
                System.out.println("消息ID = " + envelope.getDeliveryTag());

                // 改变为手动签收
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        // 监听通道
        // 第一个参数：通道名  第二个：关闭自动签收  第三个：回调
        channel.basicConsume(QUEUE_NAME, false, callback);
    }
}
